package thread

import (
	"codejy/analysis"
	"codejy/store"
	"codejy/structdef"
	"codejy/typedefault"
	"strconv"
	"sync"
)

type LockInt struct {
	Addr        string
	ThreadStore *structdef.ThreadStore
	value       int
	//读写锁
	lock sync.RWMutex
}

func (f *LockInt) CreateTypeDefault(addr string, threadStore *structdef.ThreadStore, parameter ...string) {
	//判断是int
	value := parameter[0]
	var v1 int
	if value != `""` { //如果不是空,那么就是有参数的
		isInt := analysis.IsInt(value)
		if !isInt {
			panic("LockInt 必须是整数")
		}
		v, _ := strconv.Atoi(value)
		v1 = v
	} else { //如果是空,那么就是没有参数的,默认为0
		v1 = 0
	}
	fUtil := &LockInt{
		Addr:        addr,
		ThreadStore: threadStore,
		value:       v1,
		lock:        sync.RWMutex{},
	}
	store.AddTypeDefaultInstanceStore(threadStore, f.GetTypeName(), addr, fUtil)
}
func (f *LockInt) GetData() interface{} {
	return nil
}

func (a *LockInt) ToStr() string {
	return ""
}
func (a *LockInt) ParameterProcessing(parameter []string) []string {
	return parameter
}

// 锁设置值
func (a *LockInt) Set(value string) {
	a.lock.Lock()
	defer a.lock.Unlock()
	//将value转换为int64
	v, _ := strconv.Atoi(value)
	a.value = v
}

// 锁获取值
func (a *LockInt) Get() string {
	a.lock.RLock()
	defer a.lock.RUnlock()
	return strconv.Itoa(a.value)
}

// 锁加
func (a *LockInt) Add(value string) string {
	a.lock.Lock()
	defer a.lock.Unlock()
	//将value转换为int64
	v, _ := strconv.Atoi(value)
	a.value = a.value + v
	return strconv.Itoa(a.value)
}

func (f *LockInt) GetDef() string {
	return `
		@CodeManual(def="new("LockInt",$1)",des="线程安全的整数变量操作 ,读写锁模式,参数为整数")
		type  LockInt{
			def init{
				core&CreateTypeDefault($1)
			}
			@CodeManual(def="set($1)",des="设置值(线程安全)")
			def set{
				core&Set($1)
			}
			@CodeManual(def="get()",des="获取值,不一定是最新的值")
			def get{
				to core&Get()
			}
			@CodeManual(def="add($1)",des="在原值上加上$1,返回新值，线程安全")
			def add{
				to core&Add($1)
			}
		}
	`
}

func init() {
	typedefault.RegisterTypeDefault(&LockInt{})
}
func (f *LockInt) GetTypeName() string {
	return "LockInt"
}
